import { Component, Injectable, Injector, OnInit } from '@angular/core';
import { environment } from '@env/environment';
import { UniversalTablesUtil } from '../../../core/universal-tables.util';
import { UploadFile, UploadXHRArgs } from 'ng-zorro-antd';
import { HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';

@Injectable({ providedIn: 'root' })

@Component({
  selector: 'app-repairformtable',
  templateUrl: './table.component.html'
})
export class RepairFormTableComponent extends UniversalTablesUtil implements OnInit {
  baseUrl: string = environment.apiBase + '/csmis';
  searchKeys: string[] = ['no'];
  apiAddress: string;
  uploading = false; // 文件上传时的加载
  currId: string;
  recognition = 'id';

  customReq = (item: UploadXHRArgs) => {
    // 构建一个 FormData 对象，用于存储文件或其他参数
    const formData = new FormData();
    formData.append('applyFile', item.file as any);
    formData.append('id', this.currId as string);
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress: true,
      withCredentials: true
    });
    // 始终返回一个 `Subscription` 对象，nz-upload 会在适当时机自动取消订阅
    return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      const newEvent: any = event;
      if (newEvent.type == HttpEventType.UploadProgress) {
        if (newEvent.total > 0) {
          (newEvent as any).percent = newEvent.loaded / newEvent.total * 100;
        }
        // 处理上传进度条，必须指定 `percent` 属性来表示进度
        item.onProgress(newEvent, item.file);
      } else if (newEvent instanceof HttpResponse) {
        // 处理成功
        const resMess = newEvent.body.type;
        const message = newEvent.body.message;
        item.onSuccess(newEvent.body, item.file, newEvent);
        this.message.create(resMess == 'fail' ? 'warning' : resMess, message, { nzDuration: 1800 });
        setTimeout(() => this.getMainData(this.pageSize, 1, {}), 200);
      }
    }, (err) => {
      // 处理失败
      item.onError(err, item.file);
      this.message.error('上传过程发生异常！', { nzDuration: 1200 });
    });
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status == 'uploading') {
      this.uploading = true;
      return;
    }
    if (info.file.status == 'done') {
      this.uploading = false;
    }
  }

  delFile(id) {
    this.loadingData = true;
    this.delUplFile({ id }).subscribe(res => {
      this.remoteMessage(res);
    }, err => this.errorHandle(err));
  }

  // 高速铁路临时要点维修文件删除
  delUplFile(params) {
    const url = environment.apiBase + '/csmis/ymTtempworkapply/deleteFile.jwt';
    return this.http.post(url, '', params);
  }

  ngOnInit() {
    super.ngOnInit();
    this.apiAddress = environment.apiBase + '/csmis/ymTtempworkapply/upload.jwt';
  }

  constructor(private injector: Injector) {
    super(injector);
  }

}
